<?php

    /**
     * Displays an error message instead of the twitter feed.
     *
     * @param string $header The header to display when the error shows up.
     * @param string $error  The error message.
     */
    function kill($header, $error) {

        echo '<h1>'. $header .'</h1>'.
             '<p>'. $error .'</p>';
        exit();

    } // kill()
    
    /**
     * Fetches the Twitter updates list of our user, including the information about our user.
     *
     * @return array
     */
    function grabTwitterData() {
    
        $refresh_cache = false;
    
        $cache_content = file_get_contents('cache.txt');
        $cache_content = trim($cache_content);
        
            if (!$cache_content) {
        
                $refresh_cache = true;

            } else {
            
                /*
                 * let's see the last time when we cached the data.
                 */
                $cache_lines = explode("\n", $cache_content);
                $cache_date = trim($cache_lines[0]) + 0;
                
                    if ($cache_date <= 0 || $cache_date < (time() - TM_CACHE_LENGTH)) {

                        $refresh_cache = true;
                    }
            }
            
            if (!$refresh_cache) {
            
                    if (!isset($cache_lines)) {

                        $cache_lines = explode("\n", $cache_content);
                    }

                $updates_cache_data = trim($cache_lines[1]);
                $updates = json_decode($updates_cache_data);

                $user_info_cache_data = trim($cache_lines[2]);
                $user_info = json_decode($user_info_cache_data, true);
                
               
                    if (is_array($updates) && is_array($user_info)) {

                        return array('updates'  => $updates,
                                     'userinfo' => $user_info);
                    }
            }
            
        // todo, validate below actions, did we get the right JSON response?

        $updates_json_data = file_get_contents('http://api.twitter.com/1/statuses/user_timeline/'. strtolower(TWITTER_USERNAME) .'.json');
        $updates = json_decode($updates_json_data);
        
        $user_info_json_data = file_get_contents('http://api.twitter.com/1/users/show/'. strtolower(TWITTER_USERNAME) .'.json');
        $user_info = json_decode($user_info_json_data, true);
        
            /*
             * let's rewrite the cache file
             */
            if (is_array($updates) && is_array($user_info)) {

                $handle = fopen('cache.txt', 'w');
                
                    if (!$handle) {
                    
                        kill('Cache file error', 'Please make sure the <em>cache.txt</em> file is writable.');
                    }
                    
                $cache = time() ."\n". 
                         trim($updates_json_data) ."\n". 
                         trim($user_info_json_data);
                
                    if (!fwrite($handle, $cache)) {

                        kill('Cache file error', 'Cannot write to <em>cache.txt</em> file, is it writable.');
                    }

                fclose($handle);
            }

        return array('updates'  => $updates,
                     'userinfo' => $user_info);

    } // grabTwitterData()

   
    function displayTweets() {

        global $twitter_data;
    
        $twitter_data = grabTwitterData();

        require_once('themes/'. TM_THEME .'/head.php');

            foreach ($twitter_data['updates'] as $k=>$tweet) {

                $tweet_date = date('g:i A M jS', (strtotime($tweet->created_at)));
                $tweet_text = preg_replace("#(@)([A-Za-z0-9_]+)#", '<a class="user" href="http://twitter.com/$2">$1$2</a>', $tweet->text);

                // based on http://stackoverflow.com/questions/1112012/replace-url-with-a-link-using-regex-in-python
                $tweet_text = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"\\2\" class=\"uline\">\\3\\4</a>", $tweet_text);

                echo '<p class="tweet'. ($k == 0 ? ' first' : null)  .'">'. $tweet_text .'<a href="http://twitter.com/'. TWITTER_USERNAME .'/statuses/'. $tweet->id .'" class="info">'. $tweet_date .'</a></p>';
            }
            
        require_once('themes/'. TM_THEME .'/foot.php');

    } // displayTweets()
    
    /**
     * Produces the URL of the stylesheet based on current template selection.
     *
     * @param string $file_name The stylesheet file name (e.g. style.css)
     */
    function getStyleSheetURL($file_name) {
        
        $url_prefix = explode('://', TM_URL);
        return $url_prefix[0] .'://'. str_replace('//', '/', $url_prefix[1] .'/themes/'). TM_THEME .'/'. $file_name;

    } // getStyleSheetURL()
    
    /**
     * Grabs the real name of the Twitter user owning the page.
     *
     * @return string
     */
    function grabUserRealName() {
    
        $name = grabUserData('name');
        
            if (!$name) {

                return ucfirst(TWITTER_USERNAME);
            }

        return $name;

    } // grabUserRealName() 
    
    /**
     * Grabs the profile image of the Twitter user.
     *
     * @return string
     */
    function grabUserProfileImageURL() {

        return str_replace('_normal.', '_bigger.', grabUserData('profile_image_url'));

    } // grabUserProfileImageURL() 
    
    /**
     * Grabs the information regarding the Twitter user.
     *
     * @param string $data_key The key to look for when searching
     *                         information about our user.
     * @return string Or returns false in case there's no such key in the user information array.
     */
    function grabUserData($data_key) {

        global $twitter_data;
        
            if (!$twitter_data['userinfo'] 
                    || !is_array($twitter_data['userinfo'])
                        || !array_key_exists($data_key, $twitter_data['userinfo'])) {

                return false;
            }

        return $twitter_data['userinfo'][$data_key];

    } // grabUserRealName() 
    

    
?>